package com.zyf.project.binaryproto.converter.impl.dynamic;

import com.zyf.project.binaryproto.contract.DataContractEncoder;
import com.zyf.project.binaryproto.converter.impl.AbstractDynamicValueConverter;
import org.jetbrains.annotations.NotNull;
import utils.binary.impl.BytesSlice;
import utils.binary.io.BytesOutputBuffer;

import java.util.function.Function;

/**
 * @author Zhou Yifan
 */
public class DataContractValueConverter extends AbstractDynamicValueConverter {

    private DataContractEncoder contractEncoder;
    private Function<Integer, ?> arrayConstructor;

    public DataContractValueConverter(@NotNull DataContractEncoder contractEncoder, Function<Integer, ?> arrayConstructor) {
        super(contractEncoder.getContractType());
        this.contractEncoder = contractEncoder;
        this.arrayConstructor = arrayConstructor;
    }

    @Override
    public int encode(Object value, BytesOutputBuffer buffer) {
        BytesOutputBuffer contractBuffer = new BytesOutputBuffer();
        int size = contractEncoder.encode(value, contractBuffer);

        size += writeSize(size, buffer);

        buffer.write(contractBuffer);
        return size;
    }

    @Override
    public Object decode(@NotNull BytesSlice dataSlice) {
        return contractEncoder.decode(dataSlice.getInputStream());
    }

    @Override
    public Function<Integer, ?> getArrayConstructor() {
        return arrayConstructor;
    }


}
